import { Component, ReactNode } from "react";
import { View, Button, Image, Text, ScrollView } from "@tarojs/components";
import { AtList, AtListItem, AtSearchBar, AtTabs, AtTabsPane } from "taro-ui";
import i7 from "./images/i7.png";
import i1 from "./images/i1.png";

import i8 from "./images/i8.png";
import Taro from "@tarojs/taro";
import "./index.scss";
import Req, { BASE_URL } from "../../utils/request";
import { delay } from "../../utils/kit";
import { getInfo } from "../../utils/auth";

export default class SupervisionIssue extends Component {
  state = {
    value: "",
    current: 0,
    currentPage: 1,
    loading: false,
    refreshing: false,
    hasMore: true,
    total: 0,
    list: [],
    topOffset: 0,
    current2: 0,
  };
  componentDidMount(): void {
    const query = Taro.createSelectorQuery();
    query
      .select("#scroll_wrapper")
      .boundingClientRect((rect: any) => {
        this.setState({
          topOffset: rect.top,
        });
      })
      .exec();

    this.loadData();
    Taro.eventCenter.on("refreshData", this._onBackRefresh);
  }
  componentWillUnmount(): void {
    Taro.eventCenter.off("refreshData", this._onBackRefresh);
  }

  _onBackRefresh = (v) => {
    if (v.force) {
      this.setState(
        {
          value: "",
          currentPage: 1,
          current: 0,
          hasMore: true,
          list: [],
        },
        () => {
          this.loadData();
        }
      );
    }
  };
  onChange = (val: string) => {
    this.setState({
      value: val,
    });
  };
  onActionClick = () => {
    console.log("开始搜索");
  };
  handleAdd = () => {
    Taro.navigateTo({
      url: "/pages/issue-form/index",
    });
  };
  handleChangeTab = (val) => {
    console.log("vvvv", val);
    this.setState(
      {
        hasMore: true,
        currentPage: 1,
        list: [],
        current: val,
      },
      () => {
        this.loadData();
      }
    );
  };
  goToDetail = (id: string) => {
    Taro.navigateTo({
      url: `/pages/issue-detail/index?id=${id}`,
    });
  };
  loadData = () => {
    const { currentPage, list, current, current2 } = this.state;
    this.setState({
      loading: true,
    });
    let url = "/project/supervision/list";
    if (current2 === 1) {
      url = "/project/performance/list";
    }
    Req.get(
      url,
      {
        state: (function () {
          if (current === 1) {
            return "1";
          } else if (current === 2) {
            return "2";
          } else if (current === 3) {
            return "3";
          } else {
            return "";
          }
        })(),
        userId: getInfo()?.userId ?? "",
        pageNum: currentPage,
        pageSize: 10,
      },
      {
        loading: false,
      }
    )
      .then((r) => {
        if (r.total - list.length === 0 || r.rows.length < 10) {
          this.setState({
            hasMore: false,
          });
        }
        this.setState({
          refreshing: false,
          total: r.total,
          list: list.concat([...r.rows] as any),
          currentPage: currentPage + 1,
          loading: false,
        });
      })
      .catch((e) => {
        this.setState({
          refreshing: false,
          loading: false,
        });
      });
  };
  onScrollDetchEnd = () => {
    const { loading } = this.state;
    if (loading) return;
    if (this.state.hasMore) {
      delay(200).then(() => {
        this.loadData();
      });
    } else {
      this.setState({
        loading: false,
      });
    }
  };
  _refreshData = () => {
    this.setState(
      {
        value: "",
        currentPage: 1,
        loading: false,
        hasMore: true,
        total: 0,
        list: [],
      },
      () => {
        this.loadData();
      }
    );
  };
  onRefresh = (e) => {
    const { refreshing } = this.state;
    if (refreshing) return;
    this.setState(
      {
        refreshing: true,
      },
      () => {
        delay(600).then(() => {
          this._refreshData();
        });
      }
    );
  };
  render(): ReactNode {
    const tabList = [
      {
        title: "全部",
      },
      {
        title: "待整改",
      },
      {
        title: "进行中",
      },
      {
        title: "已结束",
      },
    ];
    const _stateImgs = {
      0: "#7E7E7E",
      1: "#F68B49",
      2: "#5ACAAA",
      3: "#7E7E7E",
    };
    const _stateText = {
      0: "已退回",
      1: "待整改",
      2: "进行中",
      3: "已结束",
    };
    const { list, topOffset, current2 } = this.state;
    const _getImgs = (img: string) => {
      if (img) {
        return img
          .split(",")
          .map((e) => {
            return BASE_URL + e;
          })
          .slice(0, 1);
      }
      return [i7];
    };

    const _renderPf = (list, type = 1) => {
      const colors = {
        1: "#6190e8",
        2: "#f0b616",
        3: "#5bca71",
      };
      if (list) {
        let _item = list.find((e) => e.type === type);
        if (_item) {
          return (
            <>
              <View
                style={{
                  display: "flex",
                  alignItems:'flex-start'
                }}
              >
                <View
                  style={{
                    background: colors[type],
                    color:"#fff",
                    borderRadius:'5px',
                    padding:'0 5px',
                    marginRight:'0.5em'
                  }}
                >
                  {_item.year}
                </View>
                <View>{_item.outcome}</View>
              </View>
            </>
          );
        }
      }

      return null;
    };
    return (
      <View className="ss-container app-container">
        <AtTabs
          current={current2}
          onClick={(e) => {
            this.setState(
              {
                current2: e,
                hasMore: true,
                list: [],
              },
              () => {
                this.loadData();
              }
            );
          }}
          tabList={[
            {
              title: "问题管理",
            },
            {
              title: "绩效管理",
            },
          ]}
        >
          <AtTabsPane current={current2} index={0}>
            <View className="top-header">
              <AtSearchBar
                className="em-search-bar"
                value={this.state.value}
                onChange={this.onChange}
                onActionClick={this.onActionClick}
              />
              {/* <Button onClick={this.handleAdd} className="text-button">
                <Image className="icon-1" src={i1} />
                新增
              </Button> */}
            </View>
            <AtTabs
              className="tabs-wrapper"
              onClick={this.handleChangeTab}
              current={this.state.current}
              tabList={tabList}
            >
              {tabList.map((item, index) => (
                <AtTabsPane
                  key={index}
                  current={this.state.current}
                  index={index}
                >
                  <ScrollView
                    refresherTriggered={this.state.refreshing}
                    enhanced
                    showScrollbar={false}
                    id="scroll_wrapper"
                    style={{
                      height: `calc(100vh - ${topOffset}px)`,
                    }}
                    refresherEnabled
                    onRefresherRefresh={this.onRefresh}
                    onScrollToLower={this.onScrollDetchEnd}
                    className="scroll-wrapper"
                    scrollY
                  >
                    <AtList>
                      {list.map((item: any, index) => (
                        <AtListItem
                          key={index}
                          onClick={() => {
                            this.goToDetail(item.id);
                          }}
                          className="no-arrow-space"
                          note={
                            <View className="ss-item-note">
                              {_getImgs(item.img).map((e, i) => (
                                <Image
                                  mode="aspectFill"
                                  key={i}
                                  className="ss-i-n-img"
                                  src={e}
                                />
                              ))}
                              <View className="ss-i-n-desc">
                                <Text className="ss-i-n-desc-t1 two-line-max-text">
                                  {item.title ?? "/"}
                                </Text>

                                <View className="ss-i-bottom">
                                  <Text className="ss-i-d">
                                    <View
                                      style={{
                                        paddingBottom: "10px",
                                      }}
                                    >
                                      {item.problemName}
                                    </View>
                                    {item.findDate}
                                  </Text>
                                  <View className="ss-i-state">
                                    {item.state === 3 ? (
                                      <Image
                                        src={i8}
                                        className="over-img"
                                        mode="widthFix"
                                        style={{
                                          width: "95rpx",
                                        }}
                                      />
                                    ) : (
                                      <Text
                                        style={{
                                          backgroundColor:
                                            _stateImgs[item.state],
                                        }}
                                      >
                                        {_stateText[item.state] ?? ""}
                                      </Text>
                                    )}
                                  </View>
                                </View>
                              </View>
                            </View>
                          }
                        />
                      ))}
                    </AtList>
                    <View className="em-center-text">
                      <Text>
                        {this.state.hasMore ? "加载中..." : "没有更多了"}
                      </Text>
                    </View>
                  </ScrollView>
                </AtTabsPane>
              ))}
            </AtTabs>
          </AtTabsPane>
          <AtTabsPane current={current2} index={1}>
            <ScrollView
              refresherTriggered={this.state.refreshing}
              enhanced
              showScrollbar={false}
              id="scroll_wrapper"
              style={{
                height: `calc(100vh - ${100}px)`,
              }}
              refresherEnabled
              onRefresherRefresh={this.onRefresh}
              onScrollToLower={this.onScrollDetchEnd}
              className="scroll-wrapper"
              scrollY
            >
              <AtList>
                {list.map((item: any, index: number) => (
                  <AtListItem
                    note={
                      <View
                        onClick={() => {
                          Taro.navigateTo({
                            url:
                              "/pages/performance-detail/index?id=" + item.id,
                          });
                        }}
                      >
                        <View className="performance-tr">
                          <View className="performance-label">项目名称</View>
                          <View className="performance-content">
                            {item.projectName}
                          </View>
                        </View>
                        <View className="performance-tr">
                          <View className="performance-label">期债名称</View>
                          <View className="performance-content">
                            {item.futuresBondsName}
                          </View>
                        </View>
                        <View className="performance-tr">
                          <View className="performance-label">期债年份</View>
                          <View className="performance-content">
                            {item.year}
                          </View>
                        </View>
                        <View className="performance-tr">
                          <View className="performance-label">期债年限</View>
                          <View className="performance-content">
                            {item.duration}
                          </View>
                        </View>
                        <View className="performance-tr">
                          <View className="performance-label">自评&ensp;&ensp;&ensp;</View>
                          <View className="performance-content">
                            {_renderPf(item.newList, 1)}
                          </View>
                        </View>
                        <View className="performance-tr">
                          <View className="performance-label">主管评价</View>
                          <View className="performance-content">
                            {_renderPf(item.newList, 2)}
                          </View>
                        </View>
                        <View className="performance-tr">
                          <View className="performance-label">财政评价</View>
                          <View className="performance-content">
                            {_renderPf(item.newList, 3)}
                          </View>
                        </View>
                      </View>
                    }
                  />
                ))}
              </AtList>
            </ScrollView>
          </AtTabsPane>
        </AtTabs>
      </View>
    );
  }
}
